package com.leyou.search;

import com.leyou.LySearchService;
import com.leyou.Search.clients.GoodsClient;
import com.leyou.Search.pojo.Goods;
import com.leyou.Search.repository.GoodsRepository;
import com.leyou.Search.service.IndexService;
import com.leyou.PageResult;
import item.pojo.SpuBo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = LySearchService.class)
public class CreateIndexs {
    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private IndexService indexService;

    @Autowired
    private GoodsClient goodsClient;

    @Test
    public void testCreateIndexesAndAddMapping(){
        esTemplate.createIndex(Goods.class);
        esTemplate.putMapping(Goods.class);

    }

    @Test
    public void testUpLoadData(){
        int page = 1;
        while (true){
            //查询所有的spu
            PageResult<SpuBo> spuBoPageResult = goodsClient.querySpuPage(null, null, page, 50);

            //查不到数据为空
            if (spuBoPageResult == null) {
                break;
            }

            List<Goods> goodsList = new ArrayList<>();
            spuBoPageResult.getItems().forEach(spuBo ->goodsList.add(indexService.buildGoods(spuBo)));

            this.goodsRepository.saveAll(goodsList);

            page++;
        }

    }
}
